package com.module.check.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import base.dao.GenericHibernateDao;
import base.util.Page;

import com.module.check.vo.TaskDataUrl;
import com.module.check.vo.TestimonyTask;
import com.util.PropertiesUtil;

public class TestimonyTaskDao  extends GenericHibernateDao<TestimonyTask, Long> {
private TestimonyTaskDao(){}
	
	private static TestimonyTaskDao dao;
	
	public synchronized static TestimonyTaskDao getInstance(){
		if(dao==null)
			dao = new TestimonyTaskDao();
		return dao;
	}
	
	private static String URL = "http://"+PropertiesUtil.getString("downloadHostName")+":"
	+PropertiesUtil.getString("downloadPort")+PropertiesUtil.getString("downloadPath");
	/**
	 * 查询稽查任务列表
	 * @param session
	 * @param bean
	 * @param start
	 * @param limit
	 * @return
	 * @throws SQLException
	 */
	public Page getList(Session session,TestimonyTask bean,Integer start, Integer limit)throws SQLException{
		Page page = new Page();
		StringBuffer sb = new StringBuffer();
	    StringBuffer condition = new StringBuffer();
		List<Object> params = new ArrayList<Object>();
		
		if(bean.getTaskId()!=0){
			condition.append(" and obj.taskId ="+bean.getTaskId());
//			params.add(bean.getTaskId());
		}
		
		sb.append("from TestimonyTask as obj where 1=1 ");
		sb.append(condition);
		sb.append(" order by type desc,id desc");
	
		Query query = session.createQuery(sb.toString());
		query.setFirstResult(start).setMaxResults(limit);
		Query totalQuery = session
		.createQuery("select count(*) from TestimonyTask as obj where 1=1 "+condition);

		page.setTotal((long) ((Long) totalQuery.uniqueResult()).intValue());

		page.setRows(query.list());	
		return page;
	}
	/**
	 * 返回附件下载地址
	 * @param session
	 * @param taskId
	 * @return
	 */
	public String getFileUrl(Session session,Long taskId){
		String url = "";
		StringBuffer condition = new StringBuffer();
		if(taskId!=0){
			Query taskQuery = session
			.createQuery("select id from TestimonyTask as obj where obj.taskId ="+taskId);
			List testimonyIdList = taskQuery.list();
			for (Object object : testimonyIdList) {
				Long testimonyId = (Long) object;
				condition.append(" and testimonyId="+testimonyId);
				String sql = "from TaskDataUrl where 1=1";
				Query query = session.createQuery(sql+condition);
				List<TaskDataUrl> dataUrl = query.list();
				for (TaskDataUrl taskDataUrl : dataUrl) {
					url = URL+taskDataUrl.getDataUrl()+","+url;
				}
			}
		}
		
		return url;
	}
}
